<?php
/**
 * 环信注册用户
 */

namespace App\Services\Easemob;

use Easemob\Auth;
use Easemob\User;
use Easemob\UserMetadata;

use App\Models\Member\Member;
use App\Models\Common\Country;
use App\Models\School\School;

use App\Services\Com\UtilService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserAuth  extends Base
{
    public static $config_auth = null;

    public static function auth(){
        return $auth = self::getInstance();
    }

    /** 
     * 改密码
     * @throws \Exception
     */
    public static function updateUserPassword(string $member_uuid = '')
    {
        $auth = self::auth();
        $user = new User($auth);
        return $user->updateUserPassword(UtilService::memberUuidToImAccount($member_uuid), UtilService::memberUuidToImPassword($member_uuid));
    }

    /** 
     * 获取用户在线状态 支持批量
     * @throws \Exception
     */
    public static function getUsersStatusIm(array $username_uuids = [])
    {
        $auth = self::auth();
        $user = new User($auth);
        $username_arr = [];
        // Log::info(var_export(['$username_uuids',$username_uuids], true));
        foreach ($username_uuids as $key => $value) {
            if(!empty($value)){
                $username_arr[] = UtilService::memberUuidToImAccount($value);
            }
        }
        
        $status_arr = $user->isUsersOnline($username_arr);
        // Log::info(var_export(['$status_arr',$status_arr], true));
        //匹配migo用户uuid
        $online_arr = [];
        foreach ($username_uuids as $uuid_key => $uuid_value) {
            if(!empty($uuid_value)){
                $im_uuid = UtilService::memberUuidToImAccount($uuid_value);
                $online_arr[$uuid_value] = isset($status_arr[$im_uuid]) && $status_arr[$im_uuid]==true ? 1 : 0;
            }else{
                $online_arr[$uuid_value] = 0;
            }
        }
        // Log::info(var_export(['$online_arr',$online_arr], true));
        return $online_arr;

    }

    /** 获取环信token
     * @param $param
     * {
    "
        "access_token": "YWMtEw6M7AfTEe21rN0KdzpVQJUno3LpUUStoNqO-lD0KzFWXzxwBmwR7bbu1WRp1-MGAwMAAAGCGWu2nAAJOoAIGJcUzJOPf9_HAOXWbW5sFNgwMTxiVPuZIDmknhs0jQ",
        "expires_in": 604800
    
     * @throws \Exception
     */
    public static function getToken(array $param)
    {
        $auth = self::auth();
        $im_username = UtilService::memberUuidToImAccount($param['uuid']);
        $data = array(
            'username' => $im_username,
            'password' => UtilService::memberUuidToImPassword($param['uuid']),
        );
        
        $exp_time = 3600*24*7;
        // 生成 Easemob userToken
        $res = $auth->getUserToken($data['username'], $data['password'], $exp_time);

        if(!empty($res)){
            $res['username'] = $im_username;
        }
        
        return $res;
    }

    /** 注册环信
     * @param $param['uuid']
     * @param $param['avatar_url']
     * @param $param['nickname']
     * @param $param['country_uuid']
     * @throws \Exception
     */
    public static function register(array $param)
    {
        $auth = self::auth();
        $user = new User($auth);
        
        // 注册单个用户
        $data = array(
            'username' => UtilService::memberUuidToImAccount($param['uuid']),
            'password' => UtilService::memberUuidToImPassword($param['uuid']),
            'nickname' => $param['nickname'] ?? '',
            'avatarUrl' => $param['avatar_url'] ?? '',
        );
        
        $res = $user->create($data);

        $res2 = self::metadata($param);

        return [$res, $res2];

    }

    /** 设置属性
     * members的值 
     * $param['uuid']
     * $param['state']
     * $param['country_uuid']
     * $param['school_uuid']
     * $param['avatar_url']
     * $param['nickname']
     * @throws \Exception
     */
    public static function metadata(array $param)
    {
        $ext = [
            'uuid' => $param['uuid'],
            'vip' => 0,
            'state' => $param['state'] ?? 0, //默认是注册
            'avatar_url' => $param['avatar_url'] ?? '',
            'nickname' => $param['nickname'] ?? '',
            'no' => $param['no'] ?? '',
        ];

        if(isset($param['country_uuid']) && $param['country_uuid']){
            $country_arr = Country::where('uuid', '=', $param['country_uuid'])->first();
            $ext['nationalflag'] = !empty($country_arr['nationalflag']) ? $country_arr['nationalflag'] : null;
            $ext['country'] = !empty($country_arr) ? $country_arr : null;
        }
        if(isset($param['school_uuid']) && $param['school_uuid']){
            $arr = School::where('uuid', '=', $param['school_uuid'])->first();
            $ext['school'] = $arr ?? null;
        }
        $ext_encode = json_encode($ext);


        $auth = self::auth();
        // 实例化对象
        $metadata = new UserMetadata($auth);
        // 设置用户属性

        $im_user_name = UtilService::memberUuidToImAccount($param['uuid']);
        return $metadata->setMetadataToUser($im_user_name,array('avatarurl' => $param['avatar_url'] ?? '', 'nickname' => $param['nickname'], 'ext' => $ext_encode));
    }

    /** 获取属性
     * @param $param['uuid'] migo 用户uuid
     * @param $param
     * @throws \Exception
     */
    public static function getMetadata(array $param)
    {
        $auth = self::auth();
        $param['uuid'] = UtilService::memberUuidToImAccount($param['uuid']);
        // 实例化对象
        $metadata = new UserMetadata($auth);

        // $user = new User($auth);
        
        $res = $metadata->getMetadataFromUser($param['uuid']);
        return $res;
    }

    

    
}